package org.apache.servicecomb.samples.practise.houserush.realestate.service;

import org.apache.http.HttpStatus;
import org.apache.servicecomb.samples.practise.houserush.realestate.dao.BuildingDao;
import org.apache.servicecomb.samples.practise.houserush.realestate.dao.HouseDao;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.Building;
import org.apache.servicecomb.samples.practise.houserush.realestate.entity.House;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HouseServiceImpl implements HouseService {
    @Autowired
    private HouseDao houseDao;
    @Autowired
    private BuildingDao buildingDao;
    @Override
    public House createHouse(Integer buildingId, House house) {
        Building building = buildingDao.findOne(buildingId);
        if(building != null) {
            house.setBuilding(building);
            return houseDao.save(house);
        } else {
            throw new DataRetrievalFailureException("楼栋信息不存在，无法添加房型");
        }
    }

    @Override
    public House findHouse(Integer id) {

        return houseDao.findOne(id);
    }

    @Override
    public House updateHouse(House house) {
        int id = house.getId();
        if(houseDao.exists(id)) {
            return houseDao.save(house);
        } else {
            throw new DataRetrievalFailureException("对应房源号无效，无法更新");
        }
    }

    @Override
    public void removeHouse(Integer id) {
        House house = houseDao.findOne(id);
        if(house.getState().equals("locking")) {
            throw new DataRetrievalFailureException("房源被锁定，无法删除");
        } else {
            houseDao.delete(id);
        }
    }

    @Override
    public List<House> indexHouses(Integer buildingId) {
        Building building = buildingDao.findOne(buildingId);
        if(building != null) {
            return building.getHouses();
        } else {
            throw new DataRetrievalFailureException("查询楼栋不存在");
        }
    }

    @Override
    @Transactional
    public List<House> lockHousesForSale(List<Integer> ids) {
        //根据房源的id批量查询
        List<House> houses = houseDao.findAllByIdInForUpdate(ids);

        //遍历房源如果房源已经被锁定则抛异常
        for (House house : houses) {
            if(!"new".equals(house.getState())) {
                throw new InvocationException(HttpStatus.SC_BAD_REQUEST,"","房源" + house.getId() + "已锁定");
            }

        }
        houseDao.updateLockingStatesForHouse(ids);

        //批量修改房源
        return houses;
    }

    @Override
    @Transactional
    public int updateReleaseLockingStatesForHouses(List<Integer> ids) {

        return houseDao.updateReleaseLockingStatesForHouses(ids);
    }

}
